package com.epro.dx.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.URLUtil;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baifendian.mobile.BfdAgent;
import com.epro.dx.R;
import com.epro.dx.activity.order.OrderDetailActivity;
import com.epro.dx.adapter.ProductListAdapter;
import com.epro.dx.listenner.MyAsyncTaskListenner;
import com.epro.dx.task.BaseNeedReLoginTask;
import com.epro.dx.task.GetProductsFromSkusAsyncTask;
import com.epro.dx.task.GetRecommendTask;
import com.epro.dx.task.GetRecommendTask.GetRecommendsModel;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.OnekeyFilterLocalUtil;
import com.epro.dx.widget.CustomDialog;
import com.epro.dx.widget.MyGridView;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.HitBuilders.EventBuilder;
import com.google.android.gms.analytics.Tracker;
import com.google.android.gms.analytics.ecommerce.Product;
import com.google.android.gms.analytics.ecommerce.ProductAction;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.weipu.common.DXApplication;
import com.weipu.common.DXApplication.TrackerName;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.content.api.MyCartService;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.AddressModel;
import com.weipu.common.facade.model.Goods;
import com.weipu.common.facade.model.OrderPaypalModel;
import com.weipu.common.facade.model.OrderProductModel;
import com.weipu.common.facade.model.ProductModel;
import com.weipu.common.okhttp.OkHttpHelper;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.GlobalConfig;
import com.weipu.common.util.Logger;
import com.weipu.common.util.StringUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 支付页面
 * 
 * 
 * @author hjd008
 * @version [版本号, 2014-12-26]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
/**
 * @author epro
 *
 */
/**
 * @author epro
 * 
 */
@SuppressLint("JavascriptInterface")
public class CheckoutActivity extends BaseFragmentActivity {
	/**
	 * 日志标识
	 */
	private static final String TAG = "CheckoutActivity";

	private static final String ORDER_DETAIL = "OrderDetails";

	private static final String CONTINUE_SHOPPING = "ContinueShopping";

	// /**
	// * 进度条
	// */
	// private ProgressDialog mProgDialog = null;

	private WebView webView;

	/**
	 * 订单商品list信息
	 */
	private ArrayList<OrderProductModel> orderProductModels;

	private String paypalUrl;

	private OrderPaypalModel orderPaypalModel = new OrderPaypalModel();

	/**
	 * "0"代表从购物车进来,"1"代表订单进来,剩下代表buy now
	 */
	private int activityFlag;

	private AddressModel addressModel;

	private String orderNumber;

	private Tracker tracker;

	private Intent intent;

	private String couponCode = null;

	private EventBuilder eventBuilder;

	private String currentUrl;

	private String customerid;
	
	private LinearLayout bfdProductsLayout;
	private MyGridView bfdProductList;

	private RelativeLayout contain;
	private View specialHintDialog;
	private CustomDialog customDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		tracker = ((DXApplication) getApplication())
				.getTracker(TrackerName.APP_TRACKER);
		eventBuilder = new HitBuilders.EventBuilder();
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		intent = getIntent();
		if (null != intent && null != intent.getExtras()) {
			activityFlag = intent.getExtras().getInt(
					ServerConstant.Parameter.PARAMETER_NAME_FROM_ACTIVITY);

		}
		setContentView(R.layout.activity_checkout);
		webView = (WebView) findViewById(R.id.wv_checkout);
		bfdProductsLayout = (LinearLayout) findViewById(R.id.checkout_bfd);
		bfdProductList = (MyGridView) findViewById(R.id.bfd_product_list);
		contain = (RelativeLayout) findViewById(R.id.checkout_contain);
		getDataFormActivity(intent, savedInstanceState);
		setTitleContent(R.string.title_checkout);
		setLeftBtnContent(true, -1);
		
		topbarLeftTv.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				showConfirmGiveUpPayDialog();
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		tracker.setScreenName("Pay");
		tracker.send(new HitBuilders.ScreenViewBuilder().build());
		//百分点推荐
		BfdAgent.setDebugMode(Constant.BFD_DEBUGMODEL);
		BfdAgent.onResume(getApplicationContext());
	}

	@Override
	protected void onPause() {
		super.onPause();
		tracker.setScreenName(null);
		BfdAgent.onPause(getApplicationContext());
	}

	/**
	 * 根据不同来源页面获取相对应数据
	 * 
	 * @param intent
	 *            intet数据携带使者
	 * @param savedInstanceState
	 */
	private void getDataFormActivity(Intent intent, Bundle savedInstanceState) {
		switch (activityFlag) {
		case 0:
			if (null != intent) {
				orderProductModels = intent
						.getParcelableArrayListExtra(ServerConstant.Parameter.PARAMETER_NAME_ORDER_ORDERMAP);
				addressModel = (AddressModel) intent
						.getSerializableExtra("Address");
			}
			if (null != savedInstanceState
					&& savedInstanceState.containsKey("orderProducts")) {
				orderProductModels = savedInstanceState
						.getParcelableArrayList("orderProducts");
				addressModel = (AddressModel) savedInstanceState
						.getSerializable("Address");
			}
			if (null != orderProductModels && !orderProductModels.isEmpty()) {
				// initPaypal();
				getOrderData();
				new LoadingPayPal(false, false).execute();
			}
			break;
		case 1:
		case 3:
			if (null != intent) {
				orderNumber = intent.getStringExtra("orderNumber");
				boolean isPartPay = intent.getBooleanExtra("isPartPay", false);
				double dueAmount = intent.getDoubleExtra("DueAmount", 0.00);
				Logger.i(TAG, "DueAmount " + dueAmount);
				orderPaypalModel.setOrderNumber(orderNumber);
				orderPaypalModel.setCancelUrl("http://www.google.com/");
				orderPaypalModel.setReturnUrl(Constant.SHIPPINGADRESS_URL_M);
				orderPaypalModel.setDueAmount(dueAmount);
				orderPaypalModel.setIsClearCart(intent.getBooleanExtra(
						"isClearCart", false));
				new LoadingPayPal(true, isPartPay).execute();
			}
			break;

		default:
			break;
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putParcelableArrayList("orderProducts", orderProductModels);
		outState.putSerializable("Address", addressModel);
		super.onSaveInstanceState(outState);
	}

	/**
	 * 得到订单数据
	 * 
	 * @see [类、类#方法、类#成员]
	 */
	private void getOrderData() {
		List<Goods> items = new ArrayList<Goods>();
		float sumItemTotal = 0;
		for (int i = 0; i < orderProductModels.size(); i++) {
			Goods goods = new Goods();
			goods.setName(orderProductModels.get(i).getShortHeadLine1());
			goods.setSKU(String.valueOf(orderProductModels.get(i).getSku()));
			goods.setPrice(orderProductModels.get(i).getPrice());
			goods.setQuantity(orderProductModels.get(i).getQuantity());
			sumItemTotal = sumItemTotal
					+ (orderProductModels.get(i).getPrice() * orderProductModels
							.get(i).getQuantity());
			items.add(goods);
		}
		orderPaypalModel.setShippingAddress(ActivityUtil.getShipAddress(addressModel));
		orderPaypalModel.setItems(items);
		float sumItemTotals = sumItemTotal * 100;
		orderPaypalModel.setItemsTotal(Math.round(sumItemTotals) / 100.0f);
		orderPaypalModel.setOrderTotal(Math.round(sumItemTotals) / 100.0f);
		customerid = GlobalConfig.getInstance().getUserSessionCfg()
				.getCustomerid();
		if (null == customerid || "".equals(customerid)) {
			customerid = StringUtil.getConfig(
					ServerConstant.Parameter.PARAMETER_USER_CUSTOMERID, "0");
		}
		orderPaypalModel.setCustomerID(customerid);
		orderPaypalModel.setCancelUrl("http://www.google.com/");
		orderPaypalModel.setReturnUrl(Constant.SHIPPINGADRESS_URL_M);
		orderPaypalModel.setDevice("Android_Phone");
		if (intent != null) {
			orderPaypalModel.setIsClearCart(intent.getBooleanExtra(
					"isClearCart", false));
			couponCode = intent.getStringExtra("CouponCode");
			orderPaypalModel.setCouponCode(couponCode);
		}
	}

	/**
	 * 启动Paypal支付界面
	 */
	private void launchWeb() {
		//设置WebView的高度填充屏幕
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,contain.getHeight());
		webView.setLayoutParams(params);
		// 构建商户网站 url
		bfdProductsLayout.setVisibility(View.GONE);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setBuiltInZoomControls(true);
		webView.addJavascriptInterface(new HtmlObject(), "dmsObj");
		// webView.loadDataWithBaseURL(null, "","text/html", "utf-8",null);
		// webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
		// webView.clearCache(true);
		// webView.destroyDrawingCache();
		// webView.clearHistory();
		// 监听web view中url
		webView.setWebViewClient(new WebViewClient() {

			// 结束支付界面
			boolean isEnd;

			boolean isSuccess = false;
			
			boolean isCancel = false;


			//跳过HTTPS验证
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error)
            {
            	if(GlobalConfig.getInstance().isCheckSSL()){
            		handler.proceed();
            	}else{
            		handler.cancel();
            	}
            }

			/**
			 * android平台下，在ApiLevel小于13的情况下，
			 * webview的shouldOverrideUrlLoading并不是每次都会调用。 所以需要添加平台适配。
			 * 或者将放在shouldOverrideUrlLoading中的逻辑放在onPageStarted方法中去处理。
			 */
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				// if (!mProgDialog.isShowing())
				// {
				// mProgDialog =
				// ProgressDialog.show(CheckoutActivity.this, null,
				// getString(R.string.title_dialog_load));
				// mProgDialog.setCancelable(true);
				// }

				shouldOverrideUrlLoading(view, url);
				super.onPageStarted(view, url, favicon);
			}

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				Logger.d(TAG, "url:" + url);
				currentUrl = url;
				// 订单交易完成,此处可以通过url匹配方式标识交易成功还是失败
				if (url.contains("www.google")) {
					isEnd = true;
					isCancel=true;
				}
				// else if (url.contains(Constant.CONFIRM_SUCCESS_URL_M) ||
				// url.contains(Constant.CONFIRM_FAIL_URL))
				else if (url.contains(Constant.CONFIRM_SUCCESS_URL_M)
						|| url.contains(Constant.CONFIRM_FAIL_URL_M)) {
					topbarLeftTv.setVisibility(View.GONE);
					
					AsyncTaskUtil.executeTask(new GetRecommendTask(ActivityUtil.getCustomerID(), 3,new MyAsyncTaskListenner() {
                        
                        @Override
                        public void onPreTask() {
                            // TODO Auto-generated method stub
                            
                        }
                        
                        @Override
                        public void onPostTask(String result, Object obj) {

                            //解析数据获取sku列表
                            GetRecommendsModel model =(GetRecommendsModel) obj;
                            if(model.IsSuccess && model.Skus!=null){
                                ArrayList<Integer> skus = new ArrayList<Integer>();
                                String[] splits = model.Skus.split(",");
                                for (int i = 0; i < splits.length; i++) {
                                    skus.add(Integer.parseInt(splits[i]));
                                }
                                if(skus.size()>0){
                                    AsyncTaskUtil.executeTask(new GetProductsFromSkusAsyncTask(skus,CheckoutActivity.this,0,60,Constant.SORT_POPULARITY, -2, OnekeyFilterLocalUtil.getFilterState(CheckoutActivity.this), new MyAsyncTaskListenner() {
                                        
                                        @Override
                                        public void onPreTask() {
                                        }
                                        
                                        @SuppressWarnings("unchecked")
                                        @Override
                                        public void onPostTask(String result, Object bfdProducts) {
                                            if("0".equals(result)&& bfdProducts!=null && ((ArrayList<ProductModel>)bfdProducts).size()>0){
                                                //显示推荐商品列表
                                                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
                                                webView.setLayoutParams(params);
                                                bfdProductsLayout.setVisibility(View.VISIBLE);
                                                ProductListAdapter productListAdapter = new ProductListAdapter(CheckoutActivity.this, ((ArrayList<ProductModel>)bfdProducts), false, getDensityDpi(),tracker);
                                                productListAdapter.setCurrencyCode(((ArrayList<ProductModel>)bfdProducts).get(0).getCurrencyCode(), ((ArrayList<ProductModel>)bfdProducts).get(0).getCurrencyCodeSymbol());
                                                productListAdapter.setRecommendRequestId("");
                                                bfdProductList.setAdapter(productListAdapter);
                                            }
                                            else{
                                                //隐藏推荐列表
                                                bfdProductsLayout.setVisibility(View.GONE);
                                            }
                                        }
                                    }));
                                }
                            }
                        
                        }
                    }));
					if (ServerConstant.ActionConstant.FORM_MYCART_ACTIVITY == activityFlag) {
						refreshShoppingCart();
					}

					if (url.contains(Constant.CONFIRM_SUCCESS_URL_M)
							&& (ServerConstant.ActionConstant.FORM_ORDERLIST_ACTIVITY == activityFlag || ServerConstant.ActionConstant.FORM_ORDERDETAIL_ACTIVITY == activityFlag)) {
						Intent intent = new Intent();
						CheckoutActivity.this.setResult(
								ServerConstant.Parameter.PAYMENT_RESULTCODE,
								intent);
					}
					// PAYMENT_RESULTCODE
					isEnd = true;
				}

				else if (Constant.CANCEL_URL.equals(url)) {
					AlertToast.alert(CheckoutActivity.this,
							R.string.payment_cancel, 800);
					isEnd = true;
				} else if (Constant.FAIL_URL.equals(url)) {
					AlertToast.alert(CheckoutActivity.this,
							R.string.pay_failed, 800);
					isEnd = true;
				} else if (Constant.SUCCESS_URL.equals(url)) {
					AlertToast.alert(CheckoutActivity.this,
							R.string.pay_success, 800);
					isEnd = true;
					isSuccess = true;
					// //支付成功，进行衡量交易
					// measureTransaction();
				}
				return super.shouldOverrideUrlLoading(view, url);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				// 传递给服务端 当先下单
				if (url.contains(Constant.SHIPPINGADRESS_URL_M)) {
					view.loadUrl("javascript:setDevice('" + "Android_Phone"
							+ "')");
				}

				if (isEnd) {
					paypalFinish(isSuccess,isCancel);
				}
				super.onPageFinished(view, url);
			}

		});

		// 在加载网页的时候，显示加载进度
		webView.setWebChromeClient(new WebChromeClient() {
			@Override
			public boolean onJsAlert(WebView view, String url, String message,
					JsResult result) {
				// TODO Auto-generated method stub
				return super.onJsAlert(view, url, message, result);
			}

			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				if (newProgress > 70) {
					hideAllLayout(webView);
				}
			}
		});
		// paypalUrl="https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-5Y137574PN029003R&landingpage=login";
		webView.loadUrl(paypalUrl);
        showLoadingLayout(null);
		// 设置webview焦点
		webView.requestFocus(View.FOCUS_DOWN);
	}

	private void refreshShoppingCart() {
		MyCartService myCartService = ProviderFactory
				.createMyCartServiceDBProvider();
		for (int i = 0; i < orderProductModels.size(); i++) {
			OrderProductModel opm = orderProductModels.get(i);
			// if(null!=opm){
			// int id = opm.getId();
			// OrderProductModel
			// opmSub=myCartService.getById(getApplicationContext(), id);
			// int soldQuantity=opm.getQuantity();
			// int orQuantity=opmSub.getQuantity();
			// if(soldQuantity>=orQuantity){
			// myCartService.deleteById(CheckoutActivity.this, id);
			// }else{
			// opmSub.setQuantity(orQuantity-soldQuantity);
			// myCartService.update(getApplicationContext(), opmSub);
			// }
			// }
			int id = orderProductModels.get(i).getId();
			myCartService.deleteById(CheckoutActivity.this, id);
		}
		com.epro.dx.util.GlobalConfig.getInstance().setShoppingCartChange(true);
	}

	/**
	 * 完成Paypal支付
	 * 
	 * @param isSuccess
	 *            支付是否成功
	 */
	private void paypalFinish(boolean isSuccess,boolean isCancel) {
		// System.out.println("》》》》》进入paypalFinish");
		if (isSuccess) {// 支付成功后衡量交易
		// measureTransaction();
			eventBuilder.setCategory("OrderPay").setAction(
					"Successfully：OrderNumber= " + orderNumber + " ;");
		} else {
			eventBuilder.setCategory("OrderPay").setAction(
					"Failed：OrderNumber= " + orderNumber + " ;");
			//
			if(isCancel){
				Intent intent = new Intent(CheckoutActivity.this,
						 HomeActivity.class);
						 intent.putExtra(HomeActivity.CURRENT_TAB_TAG,
						 getString(HomeActivity.titleArray[0]));
						 startActivity(intent);
						 finish();
			}
			
		}
		tracker.send(eventBuilder.build());
		// 暂时屏蔽页面的自动跳转
		// new Handler().postDelayed(new Runnable()
		// {
		// @Override
		// public void run()
		// {
		// if (activityFlag ==
		// ServerConstant.ActionConstant.FORM_MYCART_ACTIVITY)
		// {
		// Intent intent = new Intent(CheckoutActivity.this,
		// HomeActivity.class);
		// intent.putExtra(HomeActivity.CURRENT_TAB_TAG,
		// getString(HomeActivity.titleArray[2]));
		// startActivity(intent);
		// finish();
		// }
		// }
		// }, 3000);
	}

	/**
	 * 衡量交易
	 * 
	 * @see [类、类#方法、类#成员]
	 */
	private void measureTransaction() {
		// System.out.println("》》》》》开始衡量交易");
		//加入百分点推荐逻辑
		String[] itemId = null;
		double[] price = null;
		int[] quantity = null;
		
		HitBuilders.ScreenViewBuilder builder = new HitBuilders.ScreenViewBuilder();
		// System.out.println("》》orderProductModels::"+orderProductModels.size());
		if (null != orderProductModels && orderProductModels.size() != 0) {
			
			itemId = new String[orderProductModels.size()];
			price = new double[orderProductModels.size()];
			quantity = new int[orderProductModels.size()];
			
			for (int i = 0; i < orderProductModels.size(); i++) {
				OrderProductModel model = orderProductModels.get(i);
				Product product = new Product()
						.setId(String.valueOf(model.getSku()))
						.setName(model.getShortHeadLine1())
						.setQuantity(model.getQuantity())
						.setPrice(model.getPrice());
				builder.addProduct(product);
				// System.out.println("----Product"+i);
				
				itemId[i] = String.valueOf(model.getSku());
				price[i] = (double)model.getPrice();
				quantity[i] = model.getQuantity();
			}
		}

		// -增加---------------判断订单是否为空---------------------
		if (null != orderNumber) {
			// System.out.println(">>>>>订单号："+orderNumber+"--URL:"+paypalUrl);
			ProductAction productAction = new ProductAction(
					ProductAction.ACTION_PURCHASE)
			// .setTransactionId(UUID.randomUUID().toString())
					.setTransactionId(orderNumber)
					// 此次交易关联的实体（例如某家商店）。
					.setTransactionAffiliation("DX Android Phone - Online")
					// 交易的总收入，含税费和运费。
					.setTransactionRevenue(orderPaypalModel.getOrderTotal())
					// 交易的总税费。
					.setTransactionTax(0)
					// 交易的总运费。
					.setTransactionShipping(0)
					// 订单使用的Coupon
					.setTransactionCouponCode(couponCode);
			builder.setProductAction(productAction);

			// Tracker t = DXApplication.getContext().getTracker(
			// TrackerName.APP_TRACKER);
			// t.setScreenName(CheckoutActivity.class.getSimpleName());
			tracker.send(builder.build());
			
			BfdAgent.onOrder(getApplicationContext(),orderNumber,itemId,price, quantity, (double)(orderPaypalModel.getOrderTotal()));
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (null != currentUrl
					&& (currentUrl.contains(Constant.CONFIRM_SUCCESS_URL_M) || currentUrl
							.contains(Constant.CONFIRM_FAIL_URL_M))) {
                goToHome();
				return true;
			}
			// if (null != webView && webView.canGoBack()&&!isEnd)
			// {
			// webView.stopLoading();
			// webView.goBack();
			// }
			// else
			// {

			showConfirmGiveUpPayDialog();
			// }
		}
		return true;
	}

	/**
	 * 
	 * 获取paypay支付网页URL
	 * 
	 * @author hjd008
	 * @version [版本号, 2014-12-26]
	 * @see [相关类/方法]
	 * @since [产品/模块版本]
	 */
	protected class LoadingPayPal extends BaseNeedReLoginTask {
		private boolean isRePay;
		private boolean isPartPay;

		public LoadingPayPal(boolean isRePay, boolean isPartPay) {
			this.isRePay = isRePay;
			this.isPartPay = isPartPay;
		}

		@Override
		protected void onPreExecute() {
			// showWaitingDialog();
			showLoadingLayout(webView);
		}

		@Override
		protected String doInBackground(Void... params) {
		    //先获取ip，重试3次。
		    String customerIP ="";
		    int retryCount = 0;
		    while (TextUtils.isEmpty(customerIP) && retryCount<3){
		        Request.Builder builder = new Request.Builder();
		        //"https://webml01.dxqas.com/DMS/DMSPaypal/token/PaypalFrom/GetIP"
		        Request request = builder.url(Constant.GET_IP).build();
		        Call call = OkHttpHelper.getOkHttpHelperInstance().getOkHttpClient().newCall(request);
		        Response resp = null;
                try {
                    resp = call.execute();
                    Logger.w(TAG, "GetIP code: " + resp.code());
                    if(resp.isSuccessful()){
                        customerIP = resp.body().string();
                        Logger.w(TAG, "GetIP customerIP: " + customerIP);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
		        retryCount++;
		    }
		    orderPaypalModel.setCustomerIP(customerIP.replace("\"", ""));
		    
			String token=ActivityUtil.getCustomerToken();
			long customerId=ActivityUtil.getCustomerID();
			orderPaypalModel.setToken(token);
			orderPaypalModel.setCustomerID(customerId+"");
			//Token分支需要Token校验 所以需要传递Token及CustomerID给服务端
			orderPaypalModel.setCancelUrl("http://www.google.com/"+"?customerID="+customerId+"&token="+token);
			orderPaypalModel.setReturnUrl(Constant.SHIPPINGADRESS_URL_M+"?customerID="+customerId+"&token="+token);
			try {
				if (isRePay) {
					Logger.i(TAG, "isPartPay: " + isPartPay);
					if (isPartPay) {
						paypalUrl = ProviderFactory
								.createOrderServiceProvider().PartialSetMobile(
										orderPaypalModel);
					} else {
						paypalUrl = ProviderFactory
								.createOrderServiceProvider().ReSetMobile(
										orderPaypalModel);
					}

				} else {
					// paypalUrl = ProviderFactory.createOrderServiceProvider()
					// .createOrderAndSetMobile(orderPaypalModel);
					// --修改：获取URl以及订单号
					String orderData = ProviderFactory
							.createOrderServiceProvider()
							.createOrderAndSetMobile(orderPaypalModel);
					String[] datas = orderData.split("##");
					paypalUrl = datas[0];
					orderNumber = datas[1];
				}
				// 返回Url即代表订单成功 需要删除购物车产品
				if (null != paypalUrl && !"".equals(paypalUrl)) {
					if (ServerConstant.ActionConstant.FORM_MYCART_ACTIVITY == activityFlag) {
						// MyCartService myCartService = ProviderFactory
						// .createMyCartServiceDBProvider();
						// for (int i = 0; i < orderProductModels.size(); i++) {
						// int id = orderProductModels.get(i).getId();
						// myCartService.deleteById(CheckoutActivity.this, id);
						// }
						// 生成订单后衡量交易
						measureTransaction();
						// 删除同步购物车中的商品
						AsyncTaskUtil.executeTask(new ClearCart());
						com.epro.dx.util.GlobalConfig.getInstance()
								.setShoppingCartChange(true);
					}
				}
				// paypalUrl =
				// ProviderFactory.createOrderServiceProvider().setMobileCheckOut(orderPaypalModel);
				Logger.i("HH", paypalUrl);
			} catch (DxException e) {
				return e.getErrCode();
			} catch (Exception e) {
				Logger.e("CheckoutActivity", "LoadingPayPal", e);
				return e.getMessage();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (!isFinishing()) {
				// mProgDialog.cancel();
				if (null != result || !URLUtil.isNetworkUrl(paypalUrl)) {
					// hideWaitingDialog();
					if(!isRelogin){
						hideAllLayout();
						Integer resId = ServerConstant.ReturnCode.MESSAGEMAP.get(result);
						AlertToast.alert(CheckoutActivity.this,
								ServerConstant.ReturnCode.MESSAGEMAP.get(result));
						finish();
//						if (resId == R.string.cd_unarrival_address
//								|| resId == R.string.sku_address_not_match) {
//							//如果是这两种错误码，则显示自定义的对话框
//							specialTips(resId);
//						}else {
//							AlertToast.alert(CheckoutActivity.this,
//									ServerConstant.ReturnCode.MESSAGEMAP.get(result));
//						}
					}
				} else {
					// 启动web界面
					hideAllLayout(webView);
					launchWeb();
				}
			}
		}

		@Override
		protected Context setContext() {
			return CheckoutActivity.this;
		}

		@Override
		protected BaseNeedReLoginTask setTask() {
			return new LoadingPayPal(isRePay, isPartPay);
		}
	}

	/**
	 * 弹出提示对话框
	 * @param resId
	 */
	private void specialTips(Integer resId) {
		specialHintDialog = LayoutInflater.from(this).inflate(R.layout.dialog_common_hint,null);
		((TextView) specialHintDialog.findViewById(R.id.dialog_common_content)).setText(getResources().getString(resId));
		specialHintDialog.findViewById(R.id.dialog_common_exit).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (customDialog.isShowing()) {
					customDialog.dismiss();
					finish();
				}
			}
		});
		customDialog = new CustomDialog(this, 0, 0, specialHintDialog, R.style.DialogTheme);
		customDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
			@Override
			public void onDismiss(DialogInterface dialog) {
				//当对话框消失时关闭对话框
				if (!isFinishing()) {
					finish();
				}
			}
		});
		customDialog.show();
	}

	/**
	 * @author Tony 清理购物车
	 */
	protected class ClearCart extends AsyncTask<Void, Void, String> {

		MyCartService myCartService = ProviderFactory
				.createMyCartServiceDBProvider();

		@Override
		protected void onPreExecute() {
			// showWaitingDialog();
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Void... params) {
			// 首先查询本地数据库中的商品数据,
			ArrayList<OrderProductModel> orderProductModelresults = myCartService
					.selectMenusList(CheckoutActivity.this, "_id desc");
			if (orderProductModelresults != null
					&& orderProductModelresults.size() > 0) {
				// 删除本地购物车数据，服务端数据不做处理
				for (int i = 0; i < orderProductModelresults.size(); i++) {
					int id = orderProductModelresults.get(i).getId();
					myCartService.deleteById(CheckoutActivity.this, id);
				}
			}
			// else{//由服务端调用接口进行购物车的清空操作
			// //删除服务端购物车数据
			// // 获取CustomerId
			// String customerid =
			// com.weipu.common.util.GlobalConfig.getInstance()
			// .getUserSessionCfg().getCustomerid();
			// if (null == customerid || "".equals(customerid)) {
			// customerid = StringUtil.getConfig(
			// ServerConstant.Parameter.PARAMETER_USER_CUSTOMERID,
			// "0");
			// }
			// try {
			// ProviderFactory.createShoppingCartServiceProvider().clearCart(Long.parseLong(customerid));
			// } catch (NumberFormatException e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// } catch (DxException e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// }
			// }
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			// hideWaitingDialog();
			super.onPostExecute(result);
		}
	}

	private class HtmlObject {
		public HtmlObject() {

		}

		@JavascriptInterface
		public void appGotoPage(String pageAction, String orderNum) {
			if (ORDER_DETAIL.equals(pageAction)) {
				// if(null!=orderNumber){
				// String[] strs=orderNumber.split("=");
				// if(null!=strs&&strs.length>1){
				// String orderNo=strs[1];
				if (null != orderNumber && orderNumber.length() > 1) {
					goToOrderDetail(orderNumber);
				} else {
					finish();
				}

				// }
				// }
			} else if (CONTINUE_SHOPPING.equals(pageAction)) {
				goToHome();
			} else {
				finish();
			}
		}

	}

	// @Override
	// protected View setLeftBtnContent(Boolean isBackIcon, int resId) {
	//
	// if (!isBackIcon && -1 != resId) {
	// return null;
	// } else {
	// topbarLeftTv.setVisibility(View.VISIBLE);
	// topbarLeftTv.setOnClickListener(new OnClickListener() {
	// @Override
	// public void onClick(View v) {
	// // goToHome();
	// if (null != currentUrl
	// && (currentUrl
	// .contains(Constant.CONFIRM_SUCCESS_URL_M)||currentUrl
	// .contains(Constant.CONFIRM_FAIL_URL_M))) {
	// goToOrderDetail(orderNumber);
	// } else {
	// finish();
	// }
	// }
	// });
	// if (isBackIcon) {
	// topbarLeftTv.setCompoundDrawablesWithIntrinsicBounds(
	// R.drawable.selector_topbar_back, 0, 0, 0);
	// }
	// if (-1 != resId) {
	// topbarLeftTv.setText(resId);
	// }
	// }
	//
	// return topbarLeftTv;
	// }

	private void goToOrderDetail(String orderNumber) {
		if (null == orderNumber) {
			finish();
			return;
		}
		// 单击后进入详情
		Intent intent = new Intent(this, OrderDetailActivity.class);
		Bundle b = new Bundle();
		b.putString("OrderNumber", orderNumber);
		b.putString(ServerConstant.Parameter.PARAMETER_NAME_FROM_ACTIVITY,
				ServerConstant.ActionConstant.ACTION_CHECKOUT);
		// b.putSerializable("orderItemModel", orderItemModel);
		intent.putExtras(b);
		startActivity(intent);
		finish();
	}

	private void goToHome() {
		Intent intent = new Intent();
		intent.setClass(this, HomeActivity.class);
		intent.putExtra(HomeActivity.CURRENT_TAB_TAG,
				getString(HomeActivity.titleArray[0]));
		startActivity(intent);
		finish();
	}

}
